package com.zgscwjm.taobaphelper.xp;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.google.gson.Gson;
import com.zgscwjm.taobaphelper.data.AccountBean;
import com.zgscwjm.taobaphelper.data.PrivateKey;
import com.zgscwjm.taobaphelper.exutils.LsfbLog;
import com.zgscwjm.taobaphelper.exutils.MyBaseConfig;
import com.zgscwjm.taobaphelper.exutils.StringUtils;
import com.zgscwjm.taobaphelper.util.TaskData;

import org.apache.http.util.EncodingUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.zgscwjm.taobaphelper.BaseConfig.b;


/**
 * Created by zgscwjm on 17-2-28.
 */
public class FileManager {

    public static String tag = "FileManager";

    public static final String filesDirPath = "/data/data/"+MyBaseConfig.Mypackagename+"/files/";
    public static final String dataKeyPath = "/data/data/com.zgscwjm.taobaphelper/files/key.txt";
    public static final String bssidPath = "/data/data/com.zgscwjm.taobaphepler/files/bssid.txt"; //手机WLAN中，bssid其实就是无线路由的MAC地址.
    public static final String CookiesLoginParam = "_SID_"; //// TODO: 2017/3/7 这个参数应该是个键名
    public static final String UserNameParam = "USER_NAME";
    public static final String ServerStopParam = "SERVER_STOP_MSG";
    public static final String accParamPath = "/data/data/com.zgscwjm.taobaphelper/files/acc.txt";
    public static final String userIdPath = "/data/data/com.zgscwjm.taobaphelper/files/userid.txt";
    public static final String inputTypePath = "/data/data/com.zgscwjm.taobaphelper/files/input.txt";
    public static final String TBDownPath = "/data/data/com.zgscwjm.taobaphelper/downloads/taobao.apk";
    public static final String ConfigDownPath = "/data/data/com.zgscwjm.taobaphelper/downloads/config.apk";
    public static final String ConfigInstallPath = "/data/local/tmp/config.apk";
    public static final String SogouDownPath = "/data/data/com.zgscwjm.taobaphelper/downloads/sogou.apk";
    public static final String TBInstallPath = "/data/local/tmp/taobao.apk";
    public static final String SogouInstallPath = "/data/local/tmp/sogou.apk";
    public static final String downloadDirPath = "/data/data/com.zgscwjm.taobaphelper/downloads/";
    public static final String tbUserInfoPath = "/data/data/com.taobao.taobao/share_prefs/userinfo.xml";
    public static final String localUserInfoPath = "/data/data/com.zgscwjm.taobaphelper/files/userinfo.xml";
    public static final String localAliuserPath = "/data/data/com.zgscwjm.taobaphelper/databases/aliuser";
    public static final String tbAliUserPath = "/data/data/com.taobao.taobao/databases/aliuser";
    public static final String checkNeedBackTag = "Need_Back";
    public static final String TaobaoVersionCode = "TAOBAO_VERSION";
    public static final String canBackupPath = "/data/data/" + MyBaseConfig.Mypackagename + "/files/backup.txt";
    public static final String TBIsLoginParam = "TB_IS_LOGIN";
    public static final String finishNumPath = "/data/data/" + MyBaseConfig.Mypackagename + "/file/finishnum.txt";
    public static final String newBackDirPath = "/sdcard/utf7/snaps";


    public static final String uniqueKeyPath = "/system/key.txt";
    private static String mobileKey = StringUtils.EMPTY;
    private static ContentResolver mContentResolver = null;
    private static SharedPreferences mySharePreferences = null;


    /**
     * 添加数据
     *
     * @param str1
     * @param str2
     */
    public static void addTaskData(String str1, String str2) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(TaskData.COLUMN_NAME, str1);
        contentValues.put(TaskData.COLUMN_Value, str2);
        mContentResolver.insert(TaskData.CONTENT_URI, contentValues);
    }

    /**
     * 删除数据（name=str1的筛选条件）
     *
     * @param context
     * @param str1
     */
    public static void deleteDBInfo(Context context, String str1) {
        if (mContentResolver == null) {
            mContentResolver = context.getContentResolver();
        }
        mContentResolver.delete(TaskData.CONTENT_URI, "name = '" + str1 + "' ", null);
    }

    public static String readContent(String path) {
        FileInputStream fileInputStream = null;
        String str2 = null;
        String str3 = StringUtils.EMPTY;
        File file = new File(path);
        try {
            if (file.exists()) {
                fileInputStream = new FileInputStream(file);


                byte[] bArr = new byte[fileInputStream.available()];
                fileInputStream.read(bArr);
                str3 = EncodingUtils.getString(bArr, "UTF-8");
                str2 = trimValue(str3);
            }

        } catch (Exception ex) {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return str2;
    }
//    public static String readContent(String path) {
//        FileInputStream fileInputStream;
//        FileInputStream fileInputStream2;
//        Exception exception;
//        Throwable th;
//        String str2 = null;
//        String str3 = StringUtils.EMPTY;
//        File file = new File(path);
//        try {
//            if (file.exists()){
//                fileInputStream = new FileInputStream(file);
//
//                try {
//                    byte[] bArr = new byte[fileInputStream.available()];
//                    fileInputStream.read(bArr);
//                    str3 = EncodingUtils.getString(bArr, "UTF-8");
//                    str2 = trimValue(str3);
//                    try {
//                        fileInputStream.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }catch (Exception ex2){
//                    str2 = str3;
//                    fileInputStream2 = fileInputStream;
//                    exception = ex2;
//                    try{
//                        exception.printStackTrace();
//                        if (fileInputStream2!=null){
//                            try{
//                                fileInputStream2.close();
//                            }catch (IOException e3){
//                                e3.printStackTrace();
//                            }
//                        }
//                        return str2;
//                    }catch (Throwable th2){
//                        th = th2;
//                        fileInputStream = fileInputStream2;
//                        if (fileInputStream!=null){
//                            try {
//                                fileInputStream.close();
//                            }catch (IOException e32){
//                                e32.printStackTrace();
//                            }
//                        }
//
//                        throw  th;
//                    }
//                }catch (Throwable th3){
//                    th = th3;
//                    if (fileInputStream!=null){
//                        fileInputStream.close();
//                    }
//                    throw  th;
//                }
//            }
//        }catch (Exception ex4){
//            exception = ex4;
//            str2 = str3;
//            fileInputStream2 = null;
//            exception.printStackTrace();
//            if (fileInputStream2!=null){
//                fileInputStream2.close();
//            }
//            return str2;
//        }catch (Throwable th4){
//            Throwable th5 = th4;
//            fileInputStream = null;
//            th = th5;
//            if (fileInputStream!=null){
//                fileInputStream.close();
//            }
//            throw  th;
//        }
//
//
//        return str2;
//    }

    /**
     * 去掉多余的空字符
     *
     * @param value
     * @return
     */
    public static String trimValue(String value) {
        return StringUtils.isEmpty(value) ? StringUtils.EMPTY : value.trim();
    }

    public static String readKey(Context context) {
//        if (!StringUtils.isEmpty(FileManager.mobileKey))
        if (FileManager.mobileKey.isEmpty()) {
            return FileManager.mobileKey;
        }
        String readContent;
        if (new File(dataKeyPath).exists()) {
            readContent = readContent(dataKeyPath);
            mobileKey = readContent;
            if (!StringUtils.isEmpty(readContent)) {
                return mobileKey;
            }
        }

        if (new File(uniqueKeyPath).exists()) {
            readContent = b.a.b(uniqueKeyPath)
        }

//        if (new File(dataKeyPath).exists() && !StringUtils.isEmpty(FileManager.mobileKey = readContent("/data/data/"+ MyBaseConfig.packageName+"/files/key.txt"))){
//            return FileManager.mobileKey;
//        }
//        if (new File("/system/key.txt").exists() && !StringUtils.isEmpty(FileManager.mobileKey= ))
        return null;
    }


    public static String findDBInfo(Context context, String str) {
        return findDBInfo(context, str, StringUtils.EMPTY);
    }

    public static String findDBInfo(Context context, String str, String str2) {
        if (mContentResolver == null) {
            mContentResolver = context.getContentResolver();
        }

        //查找共享数据,由com.task.content.provider提供
        String query = "name = '" + str + "'";
        LsfbLog.e("query", query);
        Cursor cursor = mContentResolver.query(TaskData.CONTENT_URI, new String[]{TaskData.COLUMN_ID, TaskData.COLUMN_NAME, TaskData.COLUMN_Value}, query, null, null);
        if (cursor == null) {
            return null;
        }
        if (cursor.moveToFirst()) {
            String string = cursor.getString(cursor.getColumnIndex(TaskData.COLUMN_Value));
            if (!cursor.isClosed()) {
                cursor.close();
            }

            if (!StringUtils.isEmpty(str2)) {
                str = str2;
            }

            try {
                string = PrivateKey.DecryptPrivate(string, str);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return string;

        } else if (cursor.isClosed()) {
            return null;
        } else {
            cursor.close();
            return null;
        }
    }

    /**
     * 把字符串str2写入str1所在文件中。
     *
     * @param str1 字符串1 文件的路径
     * @param str2 字符串2 写入文件的内容
     */
    public static void writeContent(String str1, String str2) {
        int lastIndexOf = str1.lastIndexOf("/"); //查找字符串1最后一次出现"/"的地方
        if (lastIndexOf >= 0) {
            File file = new File(str1.substring(0, lastIndexOf));
            if (!file.exists()) {
                file.mkdir();
            }
            FileOutputStream f1 = null;
            try {
                File file2 = new File(str1);
                if (!file2.exists()) {
                    file2.createNewFile();
                }
                DSLogger.info("write content:" + str2 + "to file:" + file2, new Object[0]);
                FileOutputStream f2 = new FileOutputStream(file2);
                f2.write(str2.getBytes());
                f2.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static void saveDBInfo(Context context, String str1, String str2) {
        saveDBInfo(context, str1, str2, StringUtils.EMPTY);

    }

    /**
     * 这个方法好像是保存数据的。
     *
     * @param context
     * @param str1
     * @param str2
     * @param str3
     */
    public static void saveDBInfo(Context context, String str1, String str2, String str3) {
        if (mContentResolver == null) {
            mContentResolver = context.getContentResolver();
        }
        String str4 = "name = '" + str1 + "' ";
        Cursor query = mContentResolver.query(TaskData.CONTENT_URI, new String[]{TaskData.COLUMN_ID, TaskData.COLUMN_NAME, TaskData.COLUMN_Value}, str4, null, null);
        String str5 = StringUtils.EMPTY;
        if (StringUtils.isEmpty(str3)) {
            str3 = str1;
        }
        try {
            str5 = PrivateKey.EncryptPrivate(str2, str3); //加密字符串str2,str3

        } catch (Exception e) //// FIXME: 2017/3/7 原代码是：(phoneBaseInfo,e).
        {
            e.printStackTrace();
        }
        if (query == null || query.moveToFirst()) //保存加密后的字符串str5
        {
            addTaskData(str1, str5);
        } else {
            deleteDBInfo(context, str1);
            addTaskData(str1, str5);
        }
        if (!query.isClosed()) {
            query.close();
        }
    }

    public static AccountBean readAccBean() {
        try {
            if (!new File(accParamPath).exists()) {
                return null;
            }
            String readContent = readContent(accParamPath);
            return StringUtils.isEmpty(readContent) ? null : new Gson().fromJson(readContent, AccountBean.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String queryWangwangByXml(String str) {

        String readContent = readContent(str);
        if (StringUtils.isEmpty(readContent)) {
            return StringUtils.EMPTY;
        }
        String str2 = StringUtils.EMPTY;
        Matcher matcher = Pattern.compile("<string name=\"nick\">(.+?)</string>").matcher(readContent);
        if (matcher.find()) {
            str2 = matcher.group(1);
            if (!StringUtils.isEmpty(str2)) {
                return str2;
            }
        }
        Matcher matcher1 = Pattern.compile("<string name=\"username\">(.+?)</string>").matcher(readContent);
        if (matcher1.find()) {
            str2 = matcher1.group(1);
            if (!StringUtils.isEmpty(str2)) {
                return str2;
            }
        }

        return null;
    }

    public static String queryWangwangByDatabase() {
        SQLiteDatabase database = openDatabase();
        if (database == null) {
            return "data is null!!!";
        }
        Cursor rawQuery = database.rawQuery(" select loginAccount from loginHistory order by loginTime desc limit 1", null);
        String str = StringUtils.EMPTY;
        if (rawQuery.getCount() <= 0) {
            return str;
        }
        rawQuery.moveToFirst();
        str = rawQuery.getString(rawQuery.getColumnIndex("loginAccount"));
        Log.e(tag, "account: " + str);
        return str;

    }

    public static SQLiteDatabase openDatabase() {
        SQLiteDatabase sqLiteDatabase = null;
        try {
            if (new File(localAliuserPath).exists()) {
                sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(localAliuserPath, null);
            } else {
                Log.e(tag, "account : database file not exist!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqLiteDatabase;

    }

    public static boolean checkIsNeedBackUp(Context context) {
        String readSharePerf = readSharePref(context, checkNeedBackTag);
        return StringUtils.isEmpty(readSharePerf) || !readSharePerf.equals("false");
    }

    public static String readSharePref(Context context, String str) {
        if (StringUtils.isEmpty(str)) {
            return StringUtils.EMPTY;
        }
        try {


            if (mySharePreferences == null) {
                mySharePreferences = context.getSharedPreferences("setting", 0);

            }
            return mySharePreferences.getString(str, StringUtils.EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
            return StringUtils.EMPTY;
        }
    }

    public static boolean readIfCanBackup() {
        boolean canbackup = false;
        try {
            if (new File(canBackupPath).exists()) {
                canbackup = Boolean.valueOf(readContent(canBackupPath)).booleanValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return canbackup;
    }

    public static boolean readTBIsLogin(Context context) {
        String findDBinfo = findDBInfo(context, TBIsLoginParam);
        Log.e(tag, "login res" + findDBinfo);
        if (!StringUtils.isEmpty(findDBinfo)) {
            return Boolean.valueOf(findDBinfo).booleanValue();
        }
        saveDBInfo(context, TBIsLoginParam, String.valueOf(false)); //// FIXME: 2017/3/15  这句话false有点僵
        return false;
    }

    public static int readFinishNum() {
        int i = 0;
        try {

            if (new File(finishNumPath).exists()) {
                i = Integer.parseInt(readContent(finishNumPath));

            } else {
                writeContent(finishNumPath, String.valueOf(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

}
